package com.online.edu.eduservice.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.online.edu.eduservice.entity.AliyunInfo;
import com.online.edu.eduservice.entity.R;
import org.joda.time.DateTime;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Description: TODO
 * @Author hlg
 * @Date 2020\3\4 0004
 * @Version V1.0
 **/
@RestController
@RequestMapping("/eduservice/teacher")
@CrossOrigin
public class FileUploadController {


    @PostMapping("uploadTeacherImg")
    public R uploadTeacherImg(@RequestParam MultipartFile file) throws Exception {

        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = AliyunInfo.OSSENDPOINT;
        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = AliyunInfo.OSSACCESSKEYID;
        String accessKeySecret = AliyunInfo.OSSACCESSKEYSECRET;
        String bucketName = AliyunInfo.OSSBUCKETNAME;

        System.out.println(accessKeyId);

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传文件流。
        // InputStream inputStream = new FileInputStream("<yourlocalFile>");


        InputStream inputStream = file.getInputStream();

        String filename = file.getOriginalFilename();


        String uuid = UUID.randomUUID().toString();

        filename = uuid + "_" + filename;

        String filePath = new DateTime().toString("yyyy/MM/dd");

        filename = filePath + "/" + filename;

        ossClient.putObject(bucketName, filename, inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();

        String url = "http://" + bucketName + "." + endpoint + "/" + filename;

        return R.ok().data("url", url);
    }

}
